#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# @File : compare_image.py
# @Autor: FY
# @Date: 2021/12/30
# @参考链接https://www.pyimagesearch.com/2017/06/19/image-difference-with-opencv-and-python/#comment-429138
from skimage.metrics import structural_similarity as compare_ssim
import argparse
import imutils
# pip install opencv-python, 包名为cv2
import cv2

# # 读取图片
# imageA = cv2.imread(r"C:\Users\ablesky\Documents\Slide1.jpg")
# imageB = cv2.imread(r"C:\Users\ablesky\Documents\Slide14.jpg")
# # 转换为灰度图
# grayA = cv2.cvtColor(imageA, cv2.COLOR_BGR2GRAY)
# grayB = cv2.cvtColor(imageB, cv2.COLOR_BGR2GRAY)
# # cv2.imshow("greyA", grayA)
# # 计算结构图之间的相似度,score为每个点的差值,diff为相似度,值为0-1, 1为完全匹配
# (score, diff) = compare_ssim(grayA, grayB, full=True)
# diff = (diff * 255).astype("uint8")
# print("SSIM:{}".format(score))
# # 二值化
# thresh = cv2.threshold(diff, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1]
# cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# cnts = imutils.grab_contours(cnts)
# for c in cnts:
#     print(c)
#     (x, y, w, h) = cv2.boundingRect(c)
#     cv2.rectangle(imageA, (x, y), (x + w, y + h), (0, 0, 255), 2)
#     cv2.rectangle(imageB, (x, y), (x + w, y + h), (0, 0, 255), 2)
# cv2.imshow("Modified", imageB)
# cv2.imwrite("haha2.png", imageB)
# cv2.imwrite("haha1.png", imageA)
# cv2.waitKey(0)


def compare_images(imageA_path, imageB_path, imageC):
    '''
    :param imageA_path: 图片A的完整路径
    :param imageB_path: 图片B的完整路径
    :param imageC: 对比图片A与图片B的区别,保存为imageC
    :return: 成功返回True, 失败返回False
    '''
    # 读取图片
    imageA = cv2.imread(imageA_path)
    imageB = cv2.imread(imageB_path)
    # 转换为灰度图
    grayA = cv2.cvtColor(imageA, cv2.COLOR_BGR2GRAY)
    grayB = cv2.cvtColor(imageB, cv2.COLOR_BGR2GRAY)
    # cv2.imshow("greyA", grayA)
    # 计算结构图之间的相似度,score为每个点的差值,diff为相似度,值为0-1, 1为完全匹配
    (score, diff) = compare_ssim(grayA, grayB, full=True)
    diff = (diff * 255).astype("uint8")
    print("SSIM:{}".format(score))
    # 二值化
    thresh = cv2.threshold(diff, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1]
    cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    cnts = imutils.grab_contours(cnts)
    for c in cnts:
        (x, y, w, h) = cv2.boundingRect(c)
        cv2.rectangle(imageA, (x, y), (x + w, y + h), (0, 0, 255), 2)
        cv2.rectangle(imageB, (x, y), (x + w, y + h), (0, 0, 255), 2)
    cv2.imshow("Modified", imageB)
    cv2.imwrite(imageC, imageB)
    # cv2.waitKey(0)
